package io.github.cubelitblade.controllers;

import io.github.cubelitblade.models.User;
import io.github.cubelitblade.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;



@RestController
@RequestMapping("users")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public ResponseEntity<?> addUser(@RequestBody User user) {
        if (userService.addUser(user) != 0) {
            return ResponseEntity.created(
                    ServletUriComponentsBuilder
                            .fromCurrentRequest()
                            .path("/{id}")
                            .buildAndExpand(user.getId()).toUri()
            ).build();
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        return switch (userService.deleteUser(id)) {
            case 0 -> ResponseEntity.notFound().build();
            case 1 -> ResponseEntity.noContent().build();
            default -> ResponseEntity.internalServerError().build();
        };
    }

    @GetMapping
    public ResponseEntity<?> getAllUsers() {
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getUser(@PathVariable Long id) {
        User user = userService.getUser(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
        if (id.equals(user.getId())) {
            return switch (userService.updateUser(user)) {
                case 0 -> ResponseEntity.notFound().build();
                case 1 -> ResponseEntity.ok().build();
                default -> ResponseEntity.internalServerError().build();
            };
        }
        else  {
            return ResponseEntity.badRequest().build();
        }
    }
}
